import { startsWith, isArray, isFunction } from 'lodash';
import { listenProps } from './JqComponent';
import { COMPONENT_ROUTER } from './const';

var store = {};

function sortRouters(routers) {
  routers.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).reverse();;
  for (let router of routers) {
    if (Array.isArray(router.children)) {
      sortRouters(router.children);
    }
  }
  return routers;
}

export const setRouters = (routers) => {
  store.routers = sortRouters(routers);
};

export const getRouters = () => {
  return store.routers;
}

function mountedComponet($, routers, base = '') {
  $.el.html('');

  let hash = location.hash.replace('#', '') || '/';

  const hasParentRouter = $.el.parent().closest(`[${COMPONENT_ROUTER}]`).attr(COMPONENT_ROUTER);

  for (let router of routers) {
    let { path, component, children } = router;
    let fullPath = `${base}${path}`;
    if (startsWith(hash, fullPath)) {
      if (hasParentRouter) {
        // 嵌套路由，继续找子路由
        if (isArray(children)) {
          return mountedComponet($, children, fullPath);
        }
      }
      if (isFunction(component)) {
        const componentPromise = component();
        componentPromise.then(comp => {
          $.el.attr(COMPONENT_ROUTER, fullPath);
          $.el.html(comp);
          listenProps.emit('all', 'router', { ...router, hash, path: fullPath });
        });
      } else {
        $.el.attr(COMPONENT_ROUTER, fullPath);
        $.el.html(component);
        listenProps.emit('all', 'router', { ...router, hash, path: fullPath });
      }
      return;
    }
  }
}

export default {
  template: `<div ${COMPONENT_ROUTER}></div>`,
  ready($) {
    const listener = (evt) => routerChange();

    $.on('destroy', () => window.removeEventListener('hashchange', listener));
    window.addEventListener('hashchange', listener);

    routerChange();

    function routerChange() {
      let routers = getRouters();
      mountedComponet($, routers);
    };
  }
}